package com.cn.wanxi.springsecurity.controller;


import com.cn.wanxi.springsecurity.domain.User;
import com.cn.wanxi.springsecurity.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author 吉酱
 * @since 2022-09-26
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService userService;


    /**
     * @MethodName add
     * @Description 添加用户
     * @Param [user]
     * @Return com.cn.wanxi.springsecurity.domain.User
     **/
    @PreAuthorize("hasAuthority('wx:user:create')")
    @PostMapping
    public String saveUser(User user) {

        int affectedRow = userService.addUser(user);
        return affectedRow > 0 ? "保存用户信息<font color=\"green\">成功！</font>" :
                "保存用户信息<font color=\"red\">失败！</font>";
    }


    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('wx:user:delete')")
    public String removeUser(@PathVariable("id") Integer id) {

        int affectedRow = userService.deleteUserById(id);
        return affectedRow > 0 ? "移除用户信息<font color=\"green\">成功！</font>" :
                "移除用户信息<font color=\"red\">失败！</font>";
    }


    @PutMapping
    @PreAuthorize("hasAuthority('wx:user:update')")
    public String modifyUser(User user) {


        int affectedRow = userService.updateUser(user);
        return affectedRow > 0 ? "修改用户信息<font color=\"green\">成功！</font>" :
                "修改用户信息<font color=\"red\">失败！</font>";
    }


    /**
     * @MethodName findById
     * @Description 根据id查询用户
     * @Param [id]
     * @Return com.cn.wanxi.springsecurity.domain.User
     **/
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('wx:user:read')")// 授权：有 wx:user:read 权限才能做该操作
    public User findById(@PathVariable("id") Integer id) {
        return userService.getUserById(id);
    }


    @GetMapping
    @PreAuthorize("hasAuthority('wx:user:read')")// 授权：有 wx:user:read 权限才能做该操作
    public List<User> findAll(User user) {

        return userService.getAllUser(user);

    }


    @GetMapping("/test")
//    @PreAuthorize("hasAuthority('wx:user:read')")// 授权：有 wx:user:read 权限才能做该操作
    public String userTest(User user) {

        return "test............";

    }

}

